package com.aboverock.module.shiro.realms;

import com.aboverock.autoconfigure.util.JwtUtil;
import com.aboverock.core.token.JwtToken;
import com.aboverock.module.shiro.util.ShiroCacheUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * JWT认证.
 * 
 * @author Rock Wang
 *
 */
public class JwtShiroRealm extends AuthorizingRealm {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    public JwtShiroRealm() {
        setAuthorizationCachingEnabled(false);
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String jwt = token.getPrincipal().toString();
        Claims claims;
        try {
            claims = JwtUtil.getClaimByToken(jwt);
        } catch (JwtException e) {
            throw new AuthenticationException(e);
        }
        String loginName = claims.getSubject();
        
        String cacheJwt = (String) ShiroCacheUtil.getAuthecticationCache().get(loginName);

        if (jwt.equals(cacheJwt)) {
            return new SimpleAuthenticationInfo(loginName, Boolean.TRUE, getName());
        } else {
            logger.debug("Data-Smart: 请求中的jwt认证失败，缓存中的jwt为：{}", cacheJwt);
            throw new AuthenticationException("not match the token in cache");
        }
    }

}
